import {Component, OnInit, Input, OnChanges, Output, EventEmitter} from '@angular/core';
import { User } from '../user';

import {ActivatedRoute, Params, Router} from '@angular/router';
import { UserService } from '../user.service';
import { Role } from '../../role/role';
import { RoleService } from '../../role/role.service';
import { Carrier } from '../../carrier/carrier';
import { CarrierService } from '../../carrier/carrier.service';

@Component({
    selector: 'user-detail',
    templateUrl: './user-detail.component.html',
    // styleUrls: ['./user-detail.component.css']
})

export class UserDetailComponent implements OnInit {
    @Input()
    user: User;

    @Output() onVoted = new EventEmitter<boolean>();

    roles: Role[];
    carriers: Carrier[];
    constructor(
        private userService: UserService,
        private roleService: RoleService,
        private carrierService: CarrierService,
        private router: ActivatedRoute) {

    }

    ngOnInit() {
        this.router.params.forEach((params: Params) => {
            // let user_id = +params['user_id'];
            // this.userService.getUser(user_id).then(user => this.user = user);
            this.roleService.getRoles().then(roles => this.roles = roles);
            this.carrierService.getCarriers().then(carriers => this.carriers = carriers);
        });
    }

    ngOnChanges() {
        if (!this.user) {
                console.log('........');
        } else {
            console.log(this.user.user_name);

        }

    }

    goBack() {
        window.history.back();
    }

    save(): void {
        if(this.user.role_id != 2){
          this.user.carrier_id = null;
        }
        this.userService.save(this.user).then(() => this.cancel());
    }

    delete(): void {
        this.userService.delete(this.user).then(() => this.cancel());
    }

    resetPassword(): void {
        this.userService.resetPassword(this.user).then(user => this.user = user);
    }

    cancel(): void {
        this.user = null;
        this.onVoted.emit();
    }


}
